<template>
  <div class="train-wrapper w-full h-full overflow-hidden">
    <section class="tabBar flex flex-col w-full !h-full overflow-hidden">
      <el-tabs type="border-card" v-model="activeTabName" class="demo-tabs h-full">
        <el-tab-pane label="Setting" name="Setting_" class="h-full ">
          <template #label>
            <span class="custom-tabs-label flex items-center gap-1">
              <el-icon size="24">
                <Setting />
              </el-icon>
              <span class="text-xl">设置</span>
            </span>
          </template>
          <el-card class="settings-wrapper h-full px-1 py-1 overflow-scroll ">
            <div class="setting w-full " v-for="(config, index) in configList "
              :style="{ 'height': ((config.items.length + 1) * 48) + 'px' }" :key="index">
              <span class="titleStyle">{{ config.attributeName }}</span>
              <vxe-form :rules="config.formRules" title-align="left " class="w-full  pt-10 pl-6" v-bind="config" />
              <!--   -->
            </div>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="Train" name="Train" class="h-full overflow-hidden">
          <template #label>
            <span class="custom-tabs-label flex items-center gap-1">
              <el-icon size="24">
                <Platform />
              </el-icon>
              <span class="text-xl">训练</span>
            </span>
          </template>
          <el-card class="run-wrapper h-full px-1 py-1 overflow-hidden ">
            <!-- 里面分为左右结构，左边分为三个部分，右边一个部分 -->
            <div class="wrapper w-full h-full flex flex-row gap-2">
              <div class="left w-1/5 h-full flex flex-col gap-2 ">
                <div class="commonBg  runningInfo h-[130px]">
                  <p>训练回合: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ }} / {{ }}</p>
                  <p>当前精度：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ }}</p>
                </div>
                <div class=" commonBg restInfo h-[130px]">
                  <p>学习速率： &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ }}</p>
                  <p>已用时间： &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ }}</p>
                  <p>剩余时间： &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ }}</p>
                </div>
                <div class="runLog commonBg !justify-start flex-1 text-[13px] ">
                  NVIDIA GeForce RTX 3090
                  共24.00G，预留0.32G，已分配0.24G，
                  剩余23.44G
                </div>
              </div>
              <div class="right flex-1 h-full commonBg flex flex-col">
                <div class="right-header h-8">
                  评价指标 - {{ curAlgorithm }}
                </div>
                <div class="charts w-full flex-1 flex flex-col gap-5 overflow-hidden justify-center items-center">
                  <Echart class="w-240 !h-48 flex justify-center items-center" ref="chartAccuracy"
                    :options="chartOptions" />
                  <Echart class="w-240 !h-48 flex justify-center items-center" ref="chartAccuracy"
                    :options="chartOptions" />
                  <Echart class="w-240 !h-48 flex justify-center items-center" ref="chartAccuracy"
                    :options="chartOptions" />
                </div>
              </div>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </section>
    <section class="rightBar flex flex-col gap-2 w-full !h-full overflow-hidden">
      <div class="projectInfo">
        <p>项目ID：XCX123</p>
        <p>项目名称：test321 </p>
      </div>
      <div class="chooseAlgorithm flex items-center">
        <div class="title min-w-[80px] mr-2">选择算法 :</div>
        <el-select @change="reRenderConfig" class="flx-1" v-model="params.algorithm" placeholder="请选择算法">
          <el-option v-for="item in algorithmList" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div class="intro bg-[#efefef] text-[#101010] w-full h-[34%] flex items-center justify-center">
        参数设置介绍模块
      </div>
      <div v-if="activeTabName === 'Setting_'" class="trainSave bg-[#efefef] text-white w-full h-[34%] flex flex-col">
        <section class="title"> 保存训练参数 </section>
        <section class="toolBar flex flex-row w-[98%]">
          <div class="btn w-[40%] flex items-center">
            <span class="iconify cursor-pointer color-[#6c6c6c] text-xl" data-icon="mdi:content-save-settings"
              @click="saveConfigParam"></span>
            <!-- <span class="iconify color-[#6c6c6c] mx-2 text-xl" data-icon="mdi:reload"></span> -->
          </div>
          <div class="sel flex-1">
            <el-select class="" v-model="rightBarSearch" placeholder="请选择" clearable filterable>
              <el-option v-for="item in [{ label: '1', value: '1' }]" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </div>
        </section>
        <section class="content flex-1">
          <div v-if="saveParams.length > 0" class="noEempty w-[88%] mx-auto h-full" @click="clickSaveParams">
            <div class="item" v-for="item in saveParams" :key="item.title">
              {{ item.title }}
            </div>
          </div>
          <div class="empty" v-else>暂无数据</div>
        </section>
      </div>
      <div v-if="activeTabName === 'Train'" class="trainCheck bg-[#efefef] text-white w-full h-[34%] flex flex-col">
        <section class="title"> 训练检查 </section>
        <div class="checkLog  flex-1 p-4">
          <div class="w-full h-full bg-[#fff] flex flex-col gap-1 items-center justify-start ">
            <div :class="`animate__delay-${index}s`"
              class="item w-[68%] animate__animated animate__fadeInRight flex  flex-row items-center justify-between"
              v-for="(item, index) in checkedList" :key="index">
              <span class="text-[#333]">{{ item.title }}</span>
              <el-checkbox type="checkbox" v-model="item.checked" />
            </div>s
          </div>
        </div>
      </div>
      <div class="trainName w-full h-[16%] flex gap-2 justify-center items-center">
        <label>训练名称:</label>
        <el-input class="" placeholder="请输入" clearable />
      </div>
      <div class="trainBtn w-full h-[16%] flex justify-center items-center">
        <div class="train flex items-center justify-center" @click="toggleToTrain">
          <span class="trainTxt">训练</span>
        </div>
      </div>
    </section>
  </div>
</template>

<script lang="ts" setup>
import { Echart } from '@/components/Echart/index';
import { Setting, Platform } from '@element-plus/icons-vue'
import { example } from '@/utils/a-common'
import { getAllAlgorithm, getAlgorithmById } from '@/api/a-run/index'
// import jsonStr from '@/utils/a-object-detection.json'


let configList = ref()
// const that = document
let activeTabName = ref('Setting_')
let chartAccuracy = ref()
let chartOptions = ref(example as any)
const curAlgorithm = ref('目标检测')
let algorithmList = ref([] as any[])
const checkedList = ref([
  {
    title: '图库检查通过',
    checked: true,
  },
  {
    title: '数据集检查通过',
    checked: true,
  },
  {
    title: '模型检查通过',
    checked: true,
  }
])
const params = reactive({
  algorithm: '',
  pageNo: 1,
  pageSize: 100
})
const saveParams = ref([
  { title: 'test01', params: {} },
  { title: 'test02', params: {} },
  { title: 'test03', params: {} }
])
const rightBarSearch = ref('')

// 保存历史训练参数，方便后续再现有基础上微调
const saveConfigParam = () => {

}

// 选中训练参数list
const clickSaveParams = (e) => {
  const fatherDom = e.target.closest('.noEempty')
  //fatherDom下的item，remove .current class
  fatherDom.querySelectorAll('.item').forEach((item) => {
    item.classList.remove('current')
  })
  e.target.classList.add('current')
}

// 训练按钮事件,主要是将配置参数整合到一个json,再加上训练名称，一起提交到后端，进行训练
const toggleToTrain = () => {
  console.log(configList.value)
}

//将后端传来的参数格式，转换为vxe-form的 options配置式 渲染的格式,主要是 items(每一个表单元素的呈现形式) 以及data(整个表单元素所有的值的集合)
function transformData(arr) {
  arr.forEach(item => {
    // 添加 items 数组和 data 对象
    item.items = [];
    item.data = {};
    item.formRules = {}
    item.titleWidth = 130
    // 遍历 children 数组并生成新的 items 元素
    item.children.forEach(child => {
      // 创建 item 对象
      const itemObj = {
        field: child.attributeCode,  // attributeCode 对应 field
        title: child.attributeName,  // attributeName 对应 title
        span: 18,
        itemRender: {
          name: '',  // 默认值，后面根据 attributeType 修改
          props: {}  // 默认值，后面根据 attributeType 修改
        }
      };

      // 根据 attributeType 设置 itemRender.name 和 itemRender.props
      switch (child.attributeType) {
        case 1: // integer
          itemObj.itemRender.name = 'VxeInput';
          itemObj.itemRender.props.type = 'integer';
          break;
        case 2: // float
          itemObj.itemRender.name = 'VxeInput';
          itemObj.itemRender.props.type = 'float';
          break;
        case 3: // select
          itemObj.itemRender.name = 'VxeSelect';
          const options = [] as any[];
          child.attributeDefault.forEach((defaultValue: any) => {
            options.push({
              label: defaultValue,
              value: defaultValue
            });
          });
          itemObj.itemRender.props = {};
          itemObj.itemRender.options = options  // Select 没有具体的 props 配置
          break;
        case 4: // switch
          itemObj.itemRender.name = 'VxeSwitch';
          itemObj.itemRender.props = {};  // Switch 没有具体的 props 配置
          break;
        default:
          itemObj.itemRender.name = 'VxeInput';  // 默认处理
          break;
      }

      // 将生成的 item 对象添加到 items 数组中
      item.items.push(itemObj);
      if (child.attributeRegex) {
        item.formRules[child.attributeCode] = [{ //压入校验规则
          type: 'string',
          required: true,
          pattern: child.attributeRegex,
          message: child.validateMessage ?? '格式有误！！！'
        }]
      }
      // 同时更新 data 对象
      item.data[child.attributeCode] = child?.attributeDefault[0] ?? '';  // 初始化为 empty string
      delete item.children; //删除 children,避免报错,vxe-form 对于这个children字段有使用,格式不对可能会报错
    });
  });

  return arr;
}

const reRenderConfig = (id) => {
  initconfig(id)
}


// 初始化动态表单配置，默认为第一个算法,可传入id,动态渲染不用的算法参数
const initconfig = async (id?) => {
  if (algorithmList.value) {
    params.algorithm = id ?? algorithmList.value[0].value
    const { param } = await getAlgorithmById(params.algorithm)
    if (param) {
      configList.value = transformData(param)
    }
  }
}


const getAlgorithm = async () => {
  const res = await getAllAlgorithm(params)
  if (res.list) {
    algorithmList.value = []
    res.list.forEach((item: any) => {
      algorithmList.value.push({
        label: item.name,
        value: item.id
      })
    })
    initconfig()
  }
}


onMounted(() => {
  getAlgorithm()
  // if (jsonStr) {
  //   // console.log(transformData(jsonStr))
  //   configList.value = transformData(jsonStr)
  // }
})
</script>

<style lang="scss" scoped>
:deep() {
  :root {
    --count: 0;
    --animate-duration: 800ms;
    --animate-delay: 0.9s;
  }
}

:root {
  --animate-duration: 800ms;
  --count: 0;
  --animate-delay: 0.9s;
}

/* 整个滚动条 */
::-webkit-scrollbar {
  /* 对应纵向滚动条的宽度 */
  width: 4px;
  /* 对应横向滚动条的宽度 */
  height: 10px;
  display: none;
}

/* 滚动条上的滚动滑块 */
::-webkit-scrollbar-thumb {
  background-color: #cccecf;
  border-radius: 32px;
}

/* 滚动条轨道 */
::-webkit-scrollbar-track {
  background-color: #d7dbdf;
  border-radius: 32px;
}

:deep() {
  .el-tabs--border-card>.el-tabs__content {
    padding: 4px !important;
  }
}

.run-wrapper {
  .commonBg {
    background-color: rgba(239, 239, 239, 1);
    border: 1px solid rgba(187, 187, 187, 1);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 15px;
  }
}

.settings-wrapper {
  overflow-y: scroll !important;

  &:hover {
    ::-webkit-scrollbar {
      display: block !important;
    }
  }

  :deep(.el-card__body) {
    --el-card-padding: 5px;
    column-count: 3;

    .vxe-form {
      background-color: rgba(239, 239, 239, 1) !important;
      color: rgba(16, 16, 16, 1) !important;
      font-size: 14px !important;
      text-align: center;
      font-family: -regular;


      .vxe-input--wrapper {
        background-color: rgb(243, 247, 251) !important;
      }
    }

    .vxe-form .vxe-form--item:not(.is--vertical) .vxe-form--item-title {
      min-height: 0 !important;
      height: 36px !important;
    }

    .vxe-form .vxe-form--item .vxe-form--item-content {
      min-height: 0 !important;
      margin-bottom: 6px !important;
      height: 36px !important;
    }

    .setting {
      border: 1px solid rgba(187, 187, 187, 1);
      margin-bottom: 20px;
      background-color: rgba(239, 239, 239, 1);
      overflow-y: scroll;
      position: relative;

      .titleStyle {
        left: 10px;
        top: 12px;
        z-index: 9999;
        width: 108px;
        height: 24px;
        line-height: 24px;
        color: rgba(52, 124, 175, 1);
        font-size: 18px;
        text-align: left;
        position: absolute;
        font-family: SourceHanSansSC-bold;
      }
    }
  }
}

.demo-tabs {
  :deep(.el-tabs__nav) {
    width: 100%;

    .el-tabs__item {
      flex: 1;
    }
  }
}

.train-wrapper {
  display: grid;
  grid-template-columns: 4fr 1fr;
  grid-template-rows: 1fr;
  grid-column-gap: 10px;
  grid-row-gap: 0px;

  .tabBar {
    grid-area: 1 / 1 / 2 / 2;
    height: 100%;
  }

  .rightBar {
    grid-area: 1 / 2 / 2 / 3;
    height: 100%;

    .projectInfo {
      line-height: 20px;
      background-color: rgba(255, 255, 255, 1);
      color: rgba(16, 16, 16, 1);
      font-size: 14px;
      text-align: center;
      box-shadow: 1px 3px 5px 2px rgba(154, 154, 154, 0.4);
      font-family: -regular;
      border: 1px solid rgba(187, 187, 187, 1);
    }

    .intro {
      font-size: 20px;
      border: 1px solid rgba(187, 187, 187, 0.6);
    }

    .trainSave {
      border: 1px solid rgba(187, 187, 187, 0.6);

      .title {
        padding: 10px 16px;
        height: 24px;
        line-height: 24px;
        color: rgba(52, 124, 175, 1);
        font-size: 16px;
        text-align: left;
        font-weight: bold;
        font-family: SourceHanSansSC-bold;
      }

      .toolBar {
        padding: 16px 16px;
      }

      .content {
        padding-bottom: 12px;

        .noEempty {
          margin: auto;
          cursor: pointer;
          background-color: rgba(255, 255, 255, 1);

          .item {
            &.current {
              background-color: rgba(239, 239, 239, 1);
            }

            height: 36px;
            line-height: 20px;
            line-height: 20px;
            color: rgba(-255, -255, -255, 1);
            font-size: 14px;
            text-align: left;
            display: flex;
            align-items: center;

            &:hover {
              background-color: rgba(239, 239, 239, 1);
              color: rgb(25, 25, 25);
            }
          }
        }
      }
    }

    .trainCheck {
      .title {
        padding: 10px 16px;
        height: 24px;
        line-height: 24px;
        color: rgba(52, 124, 175, 1);
        font-size: 16px;
        text-align: left;
        font-weight: bold;
        font-family: SourceHanSansSC-bold;
      }
    }

    .trainName,
    .trainBtn {
      background-color: rgba(239, 239, 239, 1);
      border: 1px solid rgba(187, 187, 187, 1);
      margin-bottom: 3px;

      .train {
        width: 82%;
        height: 62px;
        background: url('/public/bg-trainBtn.png') no-repeat center center;
        background-size: cover;
        cursor: pointer;

        .trainTxt {
          background: rgba(255, 140, 25, 0.15);
          border: 1px solid rgb(255, 140, 25, 0.2);
          border-radius: 15px;
          height: 70%;
          width: 50%;
          font-size: 34px;
          color: #efefef;
          text-align: center;
        }
      }

      label {
        width: 90px;
        height: 24px;
        line-height: 24px;
        color: rgba(52, 124, 175, 1);
        font-size: 18px;
        text-align: left;
        font-family: SourceHanSansSC-bold;
      }

      .el-input {
        width: 178px;
        height: 41px;
        line-height: 20px;
        border-radius: 5px;
        background-color: rgba(255, 255, 255, 1);
        color: rgba(136, 136, 136, 1);
        font-size: 14px;
        text-align: left;
        font-family: PingFangSC-regular;
        border: 1px solid rgba(187, 187, 187, 1);
      }
    }
  }
}
</style>
